import { addTrainingPlanUsingPost } from '@/services/backend/trainingPlanController';
import { listTrainingRuleVoByIdsUsingPost } from '@/services/backend/trainingRuleController';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Modal } from 'antd';
import React from 'react';

interface Props {
  modalVisible: boolean;
  columns: ProColumns<API.TrainingPlan>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.TrainingPlanAddRequest) => {
  const hide = message.loading('正在添加');
  console.log(fields.ruleList);
  const ids = fields.ruleList as number[];
  const res = await listTrainingRuleVoByIdsUsingPost({
    ids
  });
  const rules = res?.data ?? [];
  const ruleList = rules.map((rule) => ({
    trainingRuleId: rule.id,
    ruleName: rule.ruleName,
    status: 0,
  })) as API.TrainingRuleDto[];

  try {
    await addTrainingPlanUsingPost({
      ...fields,
      ruleList,
    });
    hide();
    message.success('创建成功');
    return true;
  } catch (error: any) {
    hide();
    message.error(`创建失败,${error.message}`);
    return false;
  }
};

const CreateModal: React.FC<Props> = (props) => {
  const { modalVisible, columns, onSubmit, onCancel } = props;

  return (
    <Modal title={'新建'} open={modalVisible} destroyOnClose footer={null} onCancel={onCancel}>
      <ProTable
        type={'form'}
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};
export default CreateModal;
